package cn.deepmax.anime.web.task;

import cn.deepmax.anime.web.Constant;
import cn.deepmax.anime.web.pojo.Section;
import cn.deepmax.anime.web.pojo.SectionImg;
import cn.deepmax.anime.web.redis.RedisTemplate;
import cn.deepmax.anime.web.support.WebDriverPool;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;

import java.util.List;
import java.util.concurrent.CountDownLatch;

@Slf4j
public class SectionTotalTask extends AbstractTask   {

    protected Section section;

    public SectionTotalTask(Section section, WebDriverPool<? extends WebDriver> pool, RedisTemplate redisTemplate, CountDownLatch latch) {
        super( pool, redisTemplate, latch);
        this.section = section;
    }

    @Override
    public void runInternal() {
        if(section.getTotal()!=null && section.getTotal()>0){
            latch.countDown();
            return;
        }
        WebDriver driver =null;
        try{
            driver = pool.getResource();
            driver.get(section.getUrl());
            WebElement element = driver.findElement(By.cssSelector("#selectpage1 > select"));
            List<WebElement> options = element.findElements(By.cssSelector("option"));
            WebElement last = options.get(options.size()-1);
            String max = last.getAttribute("value");
            if(max!=null){
                section.setTotal(Integer.valueOf(max));
            }else{
                log.info("Failed to get {} total. ", section.getIndex());
            }
            log.info("Total get for {} with value {}.", section.getIndex(), max);
            redisTemplate.set(Constant.getSectionKey(section.getIndex()), section);
        }finally {
            if(driver!=null){
                pool.returnResource(driver);
            }
            latch.countDown();
        }
    }


}
